<script setup lang="ts">
import qs from 'qs'
import type { FormInstance } from 'element-plus'
import { CircleCheck, CircleClose } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormType } from './index.ts'
import { GetBrandoffialAccountDetail, PostCreateData, PutModifyData } from '@/api/modules/brandofficial'
import { GetOptionData as GetUserOptionData } from '@/api/modules/subscriber.ts'
import detailStore from '@/store/modules/NewCacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const id = route.query.id as string
const imgDomain = 'https://img1.eprhan.cc'

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  userId: 0,
  roleId: 2,
  realName: '',
  userMobile: '',
  userStatus: 2,
  faceUrl: '',
  desp: '',
})

const OptionJson = reactive<any>({
  userIdOption: [],
})

const options = ref<any>([])

const OldMobile = ref('')

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  // eslint-disable-next-line ts/ban-ts-comment
  // @ts-expect-error
  ruleForm.value[key] = url
}

// 提交
async function SubmitData() {
  if (id) {
    // 编辑
    ruleForm.value.id = id
    PutModifyData(ruleForm.value).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'brandofficialAccountIndex' })
      }
    })
  }
  else {
    // 添加
    PostCreateData(ruleForm.value).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.emptyFormData('brandoffcialAccountFrom')
        router.push({ name: 'brandofficialAccountIndex' })
      }
    })
  }
}

onMounted(async () => {
  if (id) {
    await GetBrandoffialAccountDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('brandoffcialAccountFrom')
  }

  const params = qs.stringify({ PageIndex: 1, PageSize: 99999, UserPhone: ruleForm.value.userMobile })
  GetUserOptionData(params).then((res: any) => {
    OptionJson.userIdOption = res.data.items
  })

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('brandoffcialAccountFrom', newValue)
    }
    if (OldMobile.value !== newValue.userMobile && newValue.userMobile.length === 11) {
      const params = qs.stringify({ PageIndex: 1, PageSize: 99999, UserPhone: newValue.userMobile })
      GetUserOptionData(params).then((res: any) => {
        OptionJson.userIdOption = res.data.items
        options.value = OptionJson.userIdOption.map((item: any) => {
          return {
            label: `${item.userId}-${item.userNickName}`,
            value: item.userId,
          }
        })
        if (options.value.length !== 0) {
          ruleForm.value.userId = OptionJson.userIdOption[0].userId
          ruleForm.value.faceUrl = OptionJson.userIdOption[0].avatar
        }
        else {
          ruleForm.value.userId = 0
          ruleForm.value.faceUrl = ''
        }
      })
      OldMobile.value = newValue.userMobile
    }
  }, { deep: true })
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="用户ID(根据手机号匹配)" prop="userData">
              <el-select-v2
                v-model="ruleForm.userId"
                :options="options"
                placeholder="请选择用户"
                disabled
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="姓名" prop="realName">
              <el-input v-model="ruleForm.realName" style="max-width: 300px;" placeholder="请输入姓名" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="授权手机号">
              <el-input v-model="ruleForm.userMobile" placeholder="请输入授权手机号" />
              <div v-if="ruleForm.userMobile.length === 11">
                <div v-if="OptionJson.userIdOption.length !== 0" class="hint">
                  <el-icon color="green">
                    <CircleCheck />
                  </el-icon>
                </div>

                <div v-else class="hint">
                  <el-icon color="red">
                    <CircleClose />
                  </el-icon>
                  <span style="margin-left: 5px;color: red;">
                    匹配失败
                  </span>
                </div>
              </div>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="头像" prop="faceUrl">
              <ImageUpload
                :img-domain="ruleForm.faceUrl?.indexOf('http') === -1 ? imgDomain : ''"
                :ext="['jpg', 'png']" :size="5" :max="1" :url="ruleForm.faceUrl" @on-success="(url) => handleUploadSuccess(url, 'faceUrl')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="账户状态">
              <el-switch
                v-model="ruleForm.userStatus"
                active-text="启用"
                inactive-text="冻结"
                :active-value="1"
                :inactive-value="2"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="描述">
              <el-input v-model="ruleForm.desp" placeholder="请输入描述" type="textarea" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}

.hint {
  display: flex;
  align-items: center;
  margin-left: 10px;
}
</style>
